angular.module('starter.myController', [])

//我的
.controller('MyCtrl', function($state,$rootScope,$scope,$ionicPopup,$window,$state,MyService,$ionicModal,$sce,$cordovaImagePicker,$ionicLoading,$ionicHistory) {
	$scope.$on('$ionicView.beforeEnter', function(event, data) {
		var userId=null;
		var token=null;
		try{
			userId=JSON.parse($window.localStorage["user"] || '{}').userId;
			token=JSON.parse($window.localStorage["user"] || '{}').token;
		}catch(e){
			
		}

		if(userId==null||token==null){
			$state.go('login');
			return ;
		}
	});
	

	
	$scope.goIsCertificate=function(){
		$state.go('tab.bandCard');
	}
	
	//查询用户基本信息
	MyService.getUserInfo().then(function(response) {
		if(response.success=="success"){
			$scope.userInfo=response.data;
			
		}
	});
	
	//查询关注数和粉丝数
	MyService.myAttention().then(function(response) {
		if(response.success=="success"){
			$scope.fs=response.data.fs;
			$scope.gz=response.data.gz;
		}
	});
	
	//查询帐户余额
	MyService.getAccountByUserId().then(function(response) {
		if(response.success=="success"){
			$scope.balance=response.data;
		}
	});
	$scope.isBreak=false;
	$scope.isRepay=false;	
   //借入提示信息
	MyService.getRepayStatus().then(function(response) {
		console.log(response);
		if(response.success=="success"){
			$scope.isBreak=response.data.isBreak;
			$scope.isRepay=response.data.isRepay;
/*			$scope.isBreak="true";
			$scope.isRepay="true";*/	
		}
	});
	
	//充值
	$scope.recharge=function(){
		//查询用户基本信息
		MyService.getUserInfo().then(function(response) {
			if(response.success=="success"){
				$scope.userInfo=response.data;
						//是否完成实名认证
		if($scope.userInfo.isCertificate==0){
			//跳转去实名
	    var confirmPopup = $ionicPopup.confirm({
	       title: '系统提示',
	       cancelText: '取消',
	       okText: '去实名',
	       template: '你还没有实名绑卡！<br />'
	    });	
	    confirmPopup.then(function(res) {
	       if(res) {
	      $state.go('tab.bandCard');
	      }
	     });
			
			return ;
		}
		//是否设置交易密码
		if($scope.userInfo.isDealCode==0){
			//跳转去设置交易密码
	    var confirmPopup = $ionicPopup.confirm({
	       title: '系统提示',
	       cancelText: '取消',
	       okText: '去设密码',
	       template: '你还没有设置交易密码！<br />'
	    });	
	    confirmPopup.then(function(res) {
	       if(res) {
	      $state.go('tab.editDealCode');
	      }
	    });
			return ;
		}			
		// 弹出充值选择框
		var myPopup = $ionicPopup.show({
			template: '<div class="list">' +
				'<a class="item item-icon-left" style="padding-top:0px;padding-bottom:0px;height:50px;line-height:50px;" ng-click="zhiFuBaoRecharge()">' +
				'<i class="icon icon-my-zfb" style="color:blue;font-size:30px;"></i> 支付宝' +
				'</a>' +
				'<a class="item item-icon-left" style="padding-top:0px;padding-bottom:0px;height:50px;line-height:50px;" ng-click="bankCardRecharge()">' +
				'<i class="icon icon-my-yhk" style="color:orangered;font-size:30px;"></i> 银行卡' +
				'</a>'+
			'</div>',
			title: '请选择充值方式',
			scope: $scope,
			buttons: [
				{ text: '取消' },
			]
		});
		
		//支付宝充值
		$scope.zhiFuBaoRecharge=function(){
			//关闭弹出框
			myPopup.close();
			$state.go('tab.zhiFuBao');
		}
		
		//银行卡充值
		$scope.bankCardRecharge=function(){
			$scope.accountData={};
			var accountPopup = $ionicPopup.show({
				template: '<label class="item item-input">'+
			    '<input type="text" ng-model="accountData.account" placeholder="请输入金额">'+
				'</label>'+
				'</div>',
				title: '请输入充值金额',
				scope: $scope,
				buttons: [
					{ text: '确定',
					  onTap:function(e){
					  		
					  		var account=$scope.accountData.account;
					  		if(account==null||account==''){
								$ionicPopup.alert({title:'系统提示',template:'金额不能为空'});
								return ;
							}
							
							//验证金额
							var r = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
							if(!r.test(account)){
								$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
								return ;
							}
					  	
					  		//关闭弹出框
							myPopup.close();
							accountPopup.close();
							
							//跳转到充值界面
							var userId=null;
					        var token=null;
					        try{
					        	userId=JSON.parse($window.localStorage["user"] || '{}').userId;
					        	token=JSON.parse($window.localStorage["user"] || '{}').token;
					        }catch(e){
					        	
					        }
					        
					        //测试充值
					        $scope.bankRechargeUrl=$sce.trustAsResourceUrl(accountServerAdr+"/app/account/userRecharge.htm?userId="+userId+"&token="+token+"&account="+account);
							$ionicModal.fromTemplateUrl('templates/my/bankRecharge.html', {
							    scope: $scope,
							    animation: 'slide-in-up'
							}).then(function(modal) {
							    $scope.modal = modal;
							    $scope.modal.show();
							});
							
							//充值完成或返回到程序
							$scope.cancelBankCardPay=function(){
								$scope.modal.hide();
								//查询帐户余额
								MyService.getAccountByUserId().then(function(response) {
									if(response.success=="success"){
										$scope.balance=response.data;
									}
								});
							}
							
							
					  }
					},
				]
			});
		}
			}
		});
	}
	
	//编辑资料页面
	$scope.editInfo=function(){
		$state.go('tab.editInfo');
	}
	
	//退出当前帐号
	$scope.loginOut=function(){
		$window.localStorage["user"]=null;
		$state.go('login');
	}
	try{
		if($rootScope.pay==1){
			$rootScope.pay=0;
			$scope.recharge();
			
		 }	
	}catch(error){
		
		
	}	
})

//支付宝控制器
.controller('ZhiFuBaoCtrl', function($ionicPopup,$scope,$stateParams,$window,$state,MyService,$cordovaClipboard) {
	
	//定义数据绑定
	$scope.data={};
	MyService.getZhifubaoInfo().then(function(response){
		if(response.success=="success"){
			$scope.data=response.data;
		}
	});
	
	//完成充值
	$scope.finishRecharge=function(data){
		MyService.saveZhifubaoTradeRecharge(data).then(function(response){
		if(response.success=="success"){
			$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.my');
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	//复制支付宝账户
	$scope.copyZhibaobaoAccount=function(){
		
		try{
			$cordovaClipboard.copy($scope.data.zhibaobaoAccount).then(function () {
				
		      	$ionicPopup.alert({title:'系统提示',template:'操作成功'});
		    }, function () {
		      	$ionicPopup.alert({title:'系统提示',template:'操作失败'});
		    });
		}catch(e){
			$ionicPopup.alert({title:'系统提示',template:'操作失败'});
		}
	}
})

//关注列表
.controller('GzController', function($ionicPopup,$scope,$stateParams,$window,$state,AttentionService) {

	$scope.list =[];
	var page=0;//初始化page为0
	$scope.noMore=true;//加载更多
	//取消关注
	$scope.deleteAttention = function(attentioned,index){
		AttentionService.deleteAttention(attentioned).then(function(response){
			if(response.success=="success"){
				$scope.list.splice(index, 1);	
				$ionicPopup.alert({title:'系统提示',template:'取消关注成功'});
			}else{
				$ionicPopup.alert({title:'系统提示',template:'操作失败'});
			}
			
		});
	}
	//关注列表查询
	$scope.loadGsList = function(){
		AttentionService.getGzUserList(page).then(function(response){
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.noMore=false;
					if(page==0){
						$scope.noData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.list.push(response.data[i]);
					}
					page=page+1;
				}
			}
		});
	}
})

//粉丝列表
.controller('FsController', function($ionicPopup,$scope,$stateParams,$window,$state,AttentionService) {
	$scope.list =[];
	var page=0;//初始化page为0
	$scope.noMore=true;//加载更多

	$scope.loadFsList = function(){ 
		AttentionService.getFsUserList(page).then(function(response){
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.noMore=false;
					if(page==0){
						$scope.noData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.list.push(response.data[i]);
					}
					page=page+1;
				}
			}
		});
	}

})

//编辑资料控制器
.controller('EditInfoCtrl', function($scope,MyService,$cordovaImagePicker,CommonService,$ionicLoading,$ionicPopup) {
	
	//查询用户基本信息
	MyService.getUserInfo().then(function(response) {
		if(response.success=="success"){
			$scope.userInfo=response.data;
			
		}
	});
	
	//修改头像
	$scope.editHeadPic=function(){
		//调用手机相册
        var options = {  
            maximumImagesCount: 1,
            quality: 70
        };
        
    	$cordovaImagePicker.getPictures(options).then(function (results) {
    		if(results!=null&&results[0]!='O'&&results.length>0){
    			$ionicLoading.show({
	      			template: '上传中，请稍后...'
	    		});
	    		try{
	    			//拍照成功后执行上传
		          	CommonService.uploadPic(results[0]).then(function(response) {
		          		if(response.success=='success'){
			          		//调用修改头像的接口
			          		MyService.updateHeadPic(response.message).then(function(response) {
			          			$ionicPopup.alert({title:'系统提示',template:response.message});
			          		},function(e){
			          			$ionicPopup.alert({title:'系统提示',template:'修改头像失败'});
			          		})
			          		$scope.userInfo.headPic=response.message;
		          		}else{
		          			$ionicPopup.alert({title:'系统提示',template:response.message});
		          		}
		          		
		          		$ionicLoading.hide();
				   	},function(e){
				   		$ionicLoading.hide();
				   		$ionicPopup.alert({title:'系统提示',template:'上传失败'});
				   	});
	    		}catch(e){
	    			$ionicLoading.hide();
	    		}
    			
    		}
    		
        },function(e){
        	$ionicLoading.hide();
        });
	}
		
})

//修改银行卡
.controller('EditCardCtrl', function($scope,MyService,$ionicPopup,$state,BankNameByCardNoService) {
		//查询用户银行卡
	MyService.getBankInfoByUserId().then(function(response) {
		if(response.success=="success"){
			$scope.BankNameByCardNum=response.data;	
		}else{			
           $scope.BankNameByCardNum='';	
		}
	});
	//查询用户基本信息
	MyService.getUserInfo().then(function(response) {
		if(response.success=="success"){
			$scope.userInfo=response.data;
			console.log($scope.userInfo);
		}
	});
		
		
	//定义数据模型
	$scope.bandCardData={};
	
	var vm=$scope.vm={};
	
	vm.CityPickData = {
	    areaData: ['点击选择开户省市区'],
	    buttonClicked: function () {
	      var province=vm.CityPickData.areaData;
	      $scope.bandCardData.province=province[0]+"-"+province[1];
	    },
	    tag: '-'
	}
	 $scope.bandCardData.cardType='';
	 var confirmPopup;
	 $scope.ChangCardType=function(){
	 if ($scope.bandCardData.cardNo.indexOf(" ")>=0) {
	 $scope.bandCardData.cardNo = $scope.bandCardData.cardNo.replace(/\s/g, "");
/*	 	try{
	 	confirmPopup .close();
	 	}catch(error){
	 		
	 	}
	 	confirmPopup = $ionicPopup.alert({title:'系统提示',template:"银行卡号不能有空格"});
	 	return ;*/
	 }
	 if($scope.bandCardData.cardNo.length>=16){
	 	    $scope.bandCardData.cardNo =$scope.bandCardData.cardNo.replace(/\s/g, "");   
		 	if($scope.bandCardData.cardType==''){
		 	console.log($scope.bandCardData.cardNo);
		 	BankNameByCardNoService.getBankNameByCardNo($scope.bandCardData.cardNo).then(function(response) {
			if(response.success=="success"){
				$scope.bandCardData.cardType=response.data;
				console.log($scope.bandCardData.cardType);
			}else{
	          // $ionicPopup.alert({title:'系统提示',template:response.message})
			}
		  });	
	 	}
	 }
	 //console.log($scope.bandCardData.cardNo);
	if($scope.bandCardData.cardNo.length==0){
	 		$scope.bandCardData.cardType='';
	 }
}

	 
	//修改银行卡
	$scope.bandCard=function(bandCardData){
		var province,city;
		if(bandCardData!=null&&bandCardData!=''){
			try{
				province=bandCardData.province.split('-')[0];
				city=bandCardData.province.split('-')[1];
			}catch(e){
				
			}
		}
		
		//银行卡卡号验证
		if(bandCardData.cardNo==null||bandCardData.cardNo==''){
			$ionicPopup.alert({title:'系统提示',template:'银行卡卡号不能为空'});
			return ;
		}
		
		//省市区验证
		if(province==null||province==''||city==null||city==''){
			$ionicPopup.alert({title:'系统提示',template:'请选择所在的省市区'});
			return ;
		}
		//开户行名称验证
      if(bandCardData.bankBranch==null||bandCardData.bankBranch==''){
			$ionicPopup.alert({title:'系统提示',template:'开户银行名称不能为空'});
			return ;
		}
      console.log(bandCardData.bankBranch);
		//交易密码
		var data={};
		$scope.data=data;
		
		var myPopup = $ionicPopup.show({
		    template: '<input type="password" ng-model="data.dealCode" length="6" style="padding-left:5px;">',
		    title: '请输入交易密码',
		    scope: $scope,
		    buttons: [
		        { text: '取消' },
		        {
			        text: '<b>确定</b>',
			        type: 'button-positive',
			        onTap: function(e) {
			           if (!$scope.data.dealCode) {
			             //不允许用户关闭，除非他键入wifi密码
			             e.preventDefault();
			            } else {
			            	if(data.dealCode==null||data.dealCode==''){
								$ionicPopup.alert({title:'系统提示',template:'交易密码不能为空'});
								return ;
			            	}
			            	
			             	//执行修改操作
							MyService.updateBankCard(bandCardData.cardNo,bandCardData.cardType,
								province,city,data.dealCode,bandCardData.bankBranch)
							.then(function(response) {
								if(response.success=="success"){
									$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
										$state.go('tab.my');
									});
								}else{
									$ionicPopup.alert({title:'系统提示',template:response.message});
								}
							});
			            }
			        }
		        }
		    ]
		});
		
		
	}
})

//实名绑卡
.controller('BandCardCtrl', function($scope,$ionicPopup,MyService,$state,$stateParams,$location,BankNameByCardNoService) {
	
	//查询用户基本信息
	MyService.getUserInfo().then(function(response) {
		if(response.success=="success"){
			$scope.userInfo=response.data;
		}
	});

	//定义数据模型
	$scope.bandCardData={};
	
	var vm=$scope.vm={};
	
	vm.CityPickData = {
	    areaData: ['点击选择开户省市区'],
	    buttonClicked: function () {
	      var province=vm.CityPickData.areaData;
	      $scope.bandCardData.province=province[0]+"-"+province[1];
	    },
	    tag: '-'
	}
	
	//实名绑卡
	$scope.bandCard=function(bandCardData){
		var province,city;
		if(bandCardData!=null&&bandCardData!=''){
			try{
				province=bandCardData.province.split('-')[0];
				city=bandCardData.province.split('-')[1];
			}catch(e){
				
			}
		}
		
		//银行卡卡号验证
		if(bandCardData.cardNo==null||bandCardData.cardNo==''){
			$ionicPopup.alert({title:'系统提示',template:'银行卡卡号不能为空'});
			return ;
		}
		
		//省市区验证
		if(province==null||province==''||city==null||city==''){
			$ionicPopup.alert({title:'系统提示',template:'请选择所在的省市区'});
			return ;
		}
		
	 //开户行名称验证
      if(bandCardData.bankBranch==null||bandCardData.bankBranch==''){
			$ionicPopup.alert({title:'系统提示',template:'开户银行名称不能为空'});
			return ;
		}

		
		//执行保存操作
		MyService.checkCertificateNoAndBandCard(bandCardData.cardNo,bandCardData.cardType,
			province,city,bandCardData.name,bandCardData.certificateNo,bandCardData.bankBranch)
		.then(function(response) {
			if(response.success=="success"){
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					//根据历史记录判断应该跳到什么地方，因为该方法在两个地方用到
					var path=$location.$$path;
					if(path.contains('authBandCard')){
						//跳转到发标界面
						$state.go('tab.addProduce');
					}else{
						$state.go('tab.my');
					}
					
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	
	 $scope.bandCardData.cardType='';
	  var confirmPopup;
	 $scope.ChangCardType=function(){
	 if ($scope.bandCardData.cardNo.indexOf(" ") >=0) {
	  $scope.bandCardData.cardNo = $scope.bandCardData.cardNo.replace(/\s/g, "");
/*	 	try{
	 	confirmPopup .close();
	 	}catch(error){
	 		
	 	}
	 	confirmPopup = $ionicPopup.alert({title:'系统提示',template:"银行卡号不能有空格"});
	 	return ;*/
	 }	 	
	 if($scope.bandCardData.cardNo.length>=16){
	 	 $scope.bandCardData.cardNo = $scope.bandCardData.cardNo.replace(/\s/g, "");
		 	if($scope.bandCardData.cardType==''){
		 	BankNameByCardNoService.getBankNameByCardNo($scope.bandCardData.cardNo).then(function(response) {
			if(response.success=="success"){
				$scope.bandCardData.cardType=response.data;
			}else{
	          // $ionicPopup.alert({title:'系统提示',template:response.message})
			}
		  });	
	 	}
	 }
	if($scope.bandCardData.cardNo.length==0){
	 		$scope.bandCardData.cardType='';
	 }
	}
	
})

//修改昵称
.controller('EditNickCtrl', function($scope,$ionicPopup,MyService,$state) {
	
	//保存昵称
	$scope.saveNick=function(nickName){
		MyService.updateNickName(nickName).then(function(response) {
			if(response.success=="success"){
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.my');
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	
})

//修改登录密码控制器
.controller('UpdatePasswordCtrl', function($scope,$ionicPopup,MyService,$state,CommonService,$interval,$timeout,$window ) {
	
	var isCertificate=0;
	//查询用户基本信息
	MyService.getUserInfo().then(function(response) {
		if(response.success=="success"){
			$scope.userInfo=response.data;
			isCertificate=response.data.isCertificate;
			console.log(response);
		}
	});
	
	
	//定义数据模型
	$scope.passwordData={};
	
	//保存登录密码
	$scope.savePassword=function(passwordData){
		//验证数据
		if(isCertificate==1){			
			if(passwordData.certificateNo==null||passwordData.certificateNo==''){
				$ionicPopup.alert({title:'系统提示',template:'身份证号码不能为空'});
				return ;
			}
			
			if(passwordData.certificateNo.length!=18){
				$ionicPopup.alert({title:'系统提示',template:'身份证号码错误'});
				return ;
			}
		}
		
		//新密码验证
		if(passwordData.newPassword==null||passwordData.newPassword==''){
			$ionicPopup.alert({title:'系统提示',template:'新密码不能为空'});
			return ;
		}
		
		//短信验证码验证
		if(passwordData.smsCode==null||passwordData.smsCode==''){
			$ionicPopup.alert({title:'系统提示',template:'验证码不能为空'});
			return ;
		}
	
		//执行保存操作
		MyService.updateLoginPassword(passwordData.smsCode,passwordData.newPassword,passwordData.certificateNo).then(function(response) {
			if(response.success=="success"){
				
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){	
					$window.localStorage["user"]=null;
					$state.go('login');
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	
	
	//允许发送短信的状态,默认可发送
	$scope.sendStatus=1;
	//时间间隔为1分
	$scope.sendTime=60;
	//发送短信验证码
	$scope.sendSms=function(){
		
		//执行验证码发送
		CommonService.sendSmsCodeByUserId().then(function(response) {
			$ionicPopup.alert({title:'系统提示',template:response.message});

			if(response.success=="success"){
				//发送成功后启动读秒
				$scope.sendStatus=-1;
				var timer=$interval(function() {
					//一秒中变化一次数字
					$scope.sendTime=$scope.sendTime-1;
					if($scope.sendTime<=0){
						$scope.sendTime=0;
					}
				},1000);
				
				//1分钟后自动销毁
				$timeout(function(){
                    $interval.cancel(timer);
                    $scope.sendStatus=1;
					$scope.sendTime=60;
                },60000);
			}
		});
	}
})

//修改电话号码
.controller('UpdatePhoneCtrl', function($scope,$ionicPopup,MyService,$state,CommonService,$interval,$timeout,$window) {
	
	$scope.updatePhoneData={};
			
	//保存手机号码
	$scope.savePhone=function(updatePhoneData){
		if(updatePhoneData.phone==null||updatePhoneData.phone==''){
			$ionicPopup.alert({title:'系统提示',template:'号码不能为空'});
			return ;
		}
		
		if(updatePhoneData.smsCode==null||updatePhoneData.smsCode==''){
			$ionicPopup.alert({title:'系统提示',template:'验证码不能为空'});
			return ;
		}

		//交易密码输入框
	    $ionicPopup.show({
		    template: '<input type="password" ng-model="updatePhoneData.dealCode" style="padding-left:5px;">',
		    title: '请输入交易密码',
		    scope: $scope,
		    buttons: [
		       { text: '取消' },
		       {
		         text: '<b>确定</b>',
		         type: 'button-positive',
		         onTap: function(e) {
		         	
		         	if(updatePhoneData.dealCode==null||updatePhoneData.dealCode==''){
						$ionicPopup.alert({title:'系统提示',template:'交易密码不能为空'});
						return ;
					}

	           		//执行保存操作
					MyService.updatePhone(updatePhoneData.phone,updatePhoneData.smsCode,updatePhoneData.dealCode).then(function(response) {
						if(response.success=="success"){
							$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
								$window.localStorage["user"]=null;
		                        $state.go('login');
								//$state.go('tab.my');
							});
						}else{
							$ionicPopup.alert({title:'系统提示',template:response.message});
						}
					});

		         }
		       },
		    ]
	    });
		
	}
	

    //允许发送短信的状态,默认可发送
	$scope.sendStatus=1;
	//时间间隔为1分钟
	$scope.sendTime=60;
	//发送短信验证码
	$scope.sendSms=function(phone){
		
		//执行验证码发送
		CommonService.sendSmsCode(phone).then(function(response) {
			$ionicPopup.alert({title:'系统提示',template:response.message});

			if(response.success=="success"){
				//发送成功后启动读秒
				$scope.sendStatus=-1;
				var timer=$interval(function() {
					//一秒中变化一次数字
					$scope.sendTime=$scope.sendTime-1;
					if($scope.sendTime<=0){
						$scope.sendTime=0;
					}
				},1000);
				
				//1分钟后自动销毁
				$timeout(function(){
                    $interval.cancel(timer);
                    $scope.sendStatus=1;
					$scope.sendTime=60;
                },60000);
			}
		});
	}
})

//设置交易密码
.controller('DealCodeCtrl', function($scope,$ionicPopup,MyService,$state,CommonService,$interval,$timeout) {
	//定义数据模型
	$scope.dealCodeData={};
	
	//保存登录密码
	$scope.saveDealCode=function(dealCodeData){
		//执行保存操作
		MyService.updateDealCode(dealCodeData.dealCode,dealCodeData.smsCode).then(function(response) {
			if(response.success=="success"){
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.my');
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	
	//允许发送短信的状态,默认可发送
	$scope.sendStatus=1;
	//时间间隔为1分钟
	$scope.sendTime=60;
	//发送短信验证码
	$scope.sendSms=function(){
		
		//执行验证码发送
		CommonService.sendSmsCodeByUserId().then(function(response) {
			$ionicPopup.alert({title:'系统提示',template:response.message});

			if(response.success=="success"){
				//发送成功后启动读秒
				$scope.sendStatus=-1;
				var timer=$interval(function() {
					//一秒中变化一次数字
					$scope.sendTime=$scope.sendTime-1;
					if($scope.sendTime<=0){
						$scope.sendTime=0;
					}
				},1000);
				
				//1分钟后自动销毁
				$timeout(function(){
                    $interval.cancel(timer);
                    $scope.sendStatus=1;
					$scope.sendTime=60;
                },60000);
			}
		});
	}
})

//资金明细
.controller('CapitalDetailCtrl', function($scope,MyService,$state) {
	
	//返回
	$scope.backMy=function(){
		$state.go('tab.my');
	}
	
	//初始化数据
	$scope.accountDetails=[];//数据初始化
	var page=0;//初始化page为0
	$scope.noMore=true;//加载更多
	
	//资金明细
	$scope.loadAccountDetails=function(){
		MyService.getUserAccountDetailList(page).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.noMore=false;
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.accountDetails.push(response.data[i]);
					}
					page=page+1;
				}
			}else{
				$scope.noMore=false;
			}
	    },function(e){
	    	$scope.noMore=false;
	    });
	}
	
	//历史账单
	$scope.oldAccountDetail=function(){
		$state.go('tab.oldAccountDetail');
	}
	
})

//历史账单
.controller('OldAccountDetailCtrl', function($scope,$ionicPopup,MyService,CommonService,$interval,$timeout,$state) {
	
	$scope.status=1;
	
	$scope.changeSel=function(num){
		$scope.status=num;
	}
	
	//初始化数据
	$scope.cxbAccountDetails=[];//数据初始化
	var cxbPage=0;//初始化page为0
	$scope.cxbNoMore=true;//加载更多
	//查询诚信宝
	$scope.loadCxbAccountDetails=function(){
		MyService.getCxbAccountDetailList(cxbPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.cxbNoMore=false;
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.cxbAccountDetails.push(response.data[i]);
					}
					cxbPage=cxbPage+1;
				}
			}else{
				$scope.cxbNoMore=false;
			}
	    },function(e){
	    	$scope.cxbNoMore=false;
	    });
	}
	
	
	//查询自金融
	$scope.zjrAccountDetails=[];//数据初始化
	var zjrPage=0;//初始化page为0
	$scope.zjrNoMore=true;//加载更多
	$scope.loadZjrAccountDetails=function(){
		MyService.getZjrAccountDetailList(zjrPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.zjrNoMore=false;
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.zjrAccountDetails.push(response.data[i]);
					}
					zjrPage=zjrPage+1;
				}
			}else{
				$scope.zjrNoMore=false;
			}
	    },function(e){
	    	$scope.zjrNoMore=false;
	    });
	}
})

//提现
.controller('WithDrawCtrl', function($scope,$ionicPopup,MyService,CommonService,$interval,$timeout,$state) {
	
	$scope.data={};
	//提现操作
	$scope.withDraw=function(withDrawData){
		//验证金额是否为空
		if(withDrawData.amount==null||withDrawData.amount==''){
			$ionicPopup.alert({title:'系统提示',template:'金额不能为空'});
			return ;
		}
		
		//验证金额
		var r = /^([1-9][\d]{0,7}|0)(\.[\d]{1,2})?$/;
		if(!r.test(withDrawData.amount)){
			$ionicPopup.alert({title:'系统提示',template:'金额输入错误'});
			return ;
		}
		
		//验证交易密码
		if(withDrawData.dealCode==null||withDrawData.dealCode==''){
			$ionicPopup.alert({title:'系统提示',template:'交易密码不能为空'});
			return ;
		}
		
		//验证短信验证码
		if(withDrawData.phoneCode==null||withDrawData.phoneCode==''){
			$ionicPopup.alert({title:'系统提示',template:'短信验证码不能为空'});
			return ;
		}
		
		//执行提现
		MyService.withDrawCheckCode(withDrawData).then(function(response) {
	    	if(response.success=="success"){
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.my');
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
	    });
	}
	
	//允许发送短信的状态,默认可发送
	$scope.sendStatus=1;
	//时间间隔为1分钟
	$scope.sendTime=60;
	//发送短信验证码
	$scope.sendSms=function(){
		
		//执行验证码发送
		CommonService.sendSmsCodeByUserId().then(function(response) {
			$ionicPopup.alert({title:'系统提示',template:response.message});

			if(response.success=="success"){
				//发送成功后启动读秒
				$scope.sendStatus=-1;
				var timer=$interval(function() {
					//一秒中变化一次数字
					$scope.sendTime=$scope.sendTime-1;
					if($scope.sendTime<=0){
						$scope.sendTime=0;
					}
				},1000);
				
				//1分钟后自动销毁
				$timeout(function(){
                    $interval.cancel(timer);
                    $scope.sendStatus=1;
					$scope.sendTime=60;
                },60000);
			}
		});
	}
	
	
	
})

//投资券
.controller('InvestmentCtrl', function($ionicPopover,$timeout,$ionicPopup,$scope,$stateParams,$window,$state,InvestmentService) {
	
	//投资券获取方式
	$scope.showRule = function(){
		var alertPopup = $ionicPopup.alert({
       		template: '获取方式<br>'+
       		'1.新用户注册成功后,可获得10元投资券.<br>'+
       		'2.借款人粉丝数首次达到10的倍数时可获得10元投资券.<br>'+
       		'3.出借人每日出借人数到达20人，可获得10元投资券.<br>'+
       		'使用方式<br>'+
       		'1.单笔投资中，最多使用2张投资券<br>'+
       		'2.对同一借款人，每日只能一笔投资中使用投资券<br>'+
       		'使用投资卷<br>'+
       		'温馨提示：平台将根据不同情况定期调整使用规则，敬请留意！',
	       	title: '投资券规则',
	       	cssClass:'my-custom-popup'
	    });
	}
	
	$scope.data = {'money':0,'count':0};
	
	//用户可用券统计
	InvestmentService.loanRedUsefulDetail().then(function(response){
		if(response.countData!=null){
			$scope.data.money=response.countData.loanRedSum;
			$scope.data.count=response.countData.loanRedCount;
		}
	})
	
	var page=0;//初始化page为0
	$scope.noMore=true;//加载更多
	$scope.list=[];//数据初始化
	//查询用户列表
	$scope.loadList =function(){ 
		InvestmentService.getLoanRedList(page).then(function(response){
			$scope.$broadcast('scroll.infiniteScrollComplete');
			$scope.countData = response.countData;
			if(response.data!=null){
				if(response.data.length<=0){
					$scope.noMore=false;
					if(page==0){
						$scope.noData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){					
							$scope.list.push(response.data[i]);
						
					}
					page=page+1;
				}
			}	
		})
	}
	
})

//邀请码控制器
.controller('InviteCodeCtrl', function($ionicPopover,$timeout,$ionicPopup,$scope,$stateParams,$window,$state,InviteService,$cordovaClipboard) {
	
	//查询邀请码以及邀请码连接
	InviteService.getInviteByUserId().then(function(response){	
		if(response.success=="success"){
			$scope.inviteData=response.data;
		}

	});
	
	//复制我的邀请码
	$scope.copyInviteCode=function(inviteCode){
		try{
			$cordovaClipboard.copy($scope.inviteData.myInvite).then(function () {
				
		      	$ionicPopup.alert({title:'系统提示',template:'操作成功'});
		    }, function () {
		      	$ionicPopup.alert({title:'系统提示',template:'操作失败'});
		    });
		}catch(e){
			$ionicPopup.alert({title:'系统提示',template:'操作失败'});
		}
	}
	
	//复制推广连接
	$scope.copyInviteUrl=function(inviteUrl){
		try{
			$cordovaClipboard.copy(inviteUrl).then(function () {
		      	$ionicPopup.alert({title:'系统提示',template:'操作成功'});
		    }, function () {
		      	$ionicPopup.alert({title:'系统提示',template:'操作失败'});
		    });
		}catch(e){
			$ionicPopup.alert({title:'系统提示',template:'操作失败'});
		}
	}
	
	$scope.iData={};
	//绑定激活码
	$scope.bandCode = function(byInvite){
		
		if(byInvite==null||byInvite==''){
			$ionicPopup.alert({title:'系统提示',template:'邀请码不能为空'});
			return ;
		}
		
	    var confirmPopup = $ionicPopup.confirm({
		       title: '提示',
		       template: '邀请码绑定,每人只有一次机会,您确定要绑定吗',
		       cancelText: '取消', 	
		       okText:'确认',   
		     });
		     confirmPopup.then(function(res) {
		       	if(res) {
		       		//用户点击确定
		       		InviteService.submitInviteCode(byInvite).then(function(response){
						if(response.success=='success'){
							$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
								//操作成功，重新查询数据
								InviteService.getInviteByUserId().then(function(response){		
									if(response.success=="success"){
										$scope.inviteData=response.data;
									}
								});
							});
						}else{
							$ionicPopup.alert({title:'系统提示',template:response.message});
						}
					});
		       	}
		     });
	}
	$scope.goHelp=function(){
		
		$state.go('tab.helpInvite');
	}
	
})

//邀请码列表
.controller('InviteListCtrl', function($ionicPopup,$scope,$window,$state,InviteService) {
	var page=0;//初始化page为0
	$scope.noMore=true;//加载更多
	$scope.list=[];//数据初始化
	//查询用户列表
	$scope.loadList =function(){ 
		InviteService.getInviteList(page).then(function(response){
			$scope.$broadcast('scroll.infiniteScrollComplete');
			try{
				console.log(response);
				if(response.data==null){
					$scope.countInvited = 0;
				}else{
					$scope.countInvited = response.data.countInvited;
					$scope.oneInviteEarnings = response.data.oneInviteEarnings;
					$scope.inviteEarnings = response.data.inviteEarnings;
					$scope.twoCountInvited = response.data.twoCountInvited;
					$scope.twoInviteEarnings = response.data.twoInviteEarnings;
				}
			}catch(e){
				
			}
			
			if(response.data!=null && response.data!='null'){
				try{
				if(response.data.data.length>0&&response.data.data.length<8){
					$scope.noMore=false;
				}
				}catch(e){
				 $scope.noMore=false;		
				 return 0;
				
			       }
				if(response.data.data.length<=0){
					$scope.noMore=false;
					if(page==0){
						$scope.noData=true;
					}
				}else{
					for(var i=0;i<response.data.data.length;i++){
						$scope.list.push(response.data.data[i]);
					}
					page=page+1;
				}
			}else{
				$scope.noMore=false;
				$scope.noData=true;
			}
		},function(e){
			$scope.noMore=false;
			$scope.noData=true;
		})
	}
	
})

//帮助
.controller('HelpController',function($scope){
		$scope.name="邀请赚钱机制介绍";
	$scope.content = "成功邀请好友，邀请人和被邀请人均可获取收益，具体如下：<br>"+
"一、天下无赖注册用户可生成邀请码，通过邀请码可邀请好友注册天下无赖，获得长期收益；<br>"+
"二、当B客户绑定A客户的“邀请码”后，无论B客户“借款”或者“投资”，A客户都可以获得收益，收益计算：<br>"+
"1.A客户可获B客户每笔“投资”金额的千分之五（收益长期有效）<br>"+
"2.A客户可获B客户每笔“借款”利息的百分之五（收益长期有效）<br>"+
"三、当B客户成功邀请C客户绑定“邀请码”后，无论C客户“借款”或者“投资”，A客户仍然可以获得收益，收益计算：<br>"+
"1.A客户可获C客户每笔“投资”金额的千分之三（收益长期有效）<br>"+
"2.A客户可获C客户每笔“借款”利息的百分之三（收益长期有效）<br>"+
"四、绑定邀请码，被邀请人完成实名认证后，邀请人可获得5元投资卷<br>"+
"操作步骤：<br>"+
"1.	点击“我的”进入我的页面<br>"+
"2.	在“我的”页面点击“邀请码”<br>"+
"3.	进入“邀请码”页面，复制邀请码，将邀请码发送给好友;"
})
//二级收益列表
.controller('myInviteList',function($scope,InviteService,$stateParams){
	var customerId = $stateParams.customerId;
	console.log(customerId);
	var page=0;//初始化page为0
	$scope.noMore=true;//加载更多
	$scope.list=[];//数据初始化
	//查询用户列表
	$scope.loadList =function(){ 
		InviteService.getTwoInviteList(page,customerId).then(function(response){
			$scope.$broadcast('scroll.infiniteScrollComplete');
			try{
				console.log(response);
				if(response.data==null){
					$scope.countInvited = 0;
				}else{
					$scope.countInvited = response.data.countInvited;
					$scope.inviteEarnings = response.data.inviteEarnings;
				}
			}catch(e){
				
			}
			
			if(response.data!=null && response.data!='null'){
				try{
				if(response.data.data.length>0&&response.data.data.length<8){
					$scope.noMore=false;
				}
				}catch(e){
				 $scope.noMore=false;		
				 return 0;
				
			       }
				if(response.data.data.length<=0){
					$scope.noMore=false;
					if(page==0){
						$scope.noData=true;
					}
				}else{
					for(var i=0;i<response.data.data.length;i++){
						$scope.list.push(response.data.data[i]);
					}
					page=page+1;
				}
			}else{
				$scope.noMore=false;
				$scope.noData=true;
			}
		},function(e){
			$scope.noMore=false;
			$scope.noData=true;
		})
	}
})
//借入-短贷
.controller('BorrowDuanController', function($scope,$stateParams,$window,$state,ZjrProduceService,$ionicHistory,$ionicScrollDelegate) {
	
	//返回到我的
	$scope.backMy=function(){
		$state.go('tab.my');
		$ionicHistory.removeBackView();
	}

	//设置默认展示为当前
	$scope.borrowStatus=1;
	
	$scope.changeSel=function(v){
		$scope.borrowStatus=v;
		$ionicScrollDelegate.$getByHandle('').scrollTop();
	}
	
	//借不到钱
	$scope.toTip = function(){
		$state.go('tab.addProduceTip02');
	}
	
	//初始化当前数据
	$scope.currentProduceList=[];//数据初始化
	var cPage=0;//初始化page为0
	$scope.cNoMore=true;//加载更多
	//查询当前借入信息
	$scope.loadCurrentProduceList=function(){
		ZjrProduceService.getProduceListByUserId(0,cPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
	    		if(response.data!=null){
	    			if(response.data.length<=0){
						$scope.cNoMore=false;
						//如果是第一页，并且长度为0，说明一条数据都没有
						if(cPage==0){
							$scope.cNoData=true;
						}
					}else{
						for(var i=0;i<response.data.length;i++){
							$scope.currentProduceList.push(response.data[i]);
						}
						cPage=cPage+1;
					}
	    		}
			}else{
				$scope.cNoMore=false;
				$scope.cNoData=true;
			}
		},function(e){
			$scope.cNoMore=false;
			$scope.cNoData=true;
		});
	}
	
	//初始化已还清数据
	$scope.allReadyProduceList=[];//数据初始化
	var aPage=0;//初始化page为0
	$scope.aNoMore=true;//加载更多
	//查询已还清借入信息
	$scope.loadAllReadyProduceList=function(){
		ZjrProduceService.getProduceListByUserId(2,aPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
	    		if(response.data!=null){
	    			if(response.data.length<=0){
						$scope.aNoMore=false;
						//如果是第一页，并且长度为0，说明一条数据都没有
						if(aPage==0){
							$scope.aNoData=true;
						}
					}else{
						for(var i=0;i<response.data.length;i++){
							$scope.allReadyProduceList.push(response.data[i]);
						}
						aPage=aPage+1;
					}
	    		}else{
	    			$scope.aNoMore=false;
					//如果为null设置为没有数据图片
					$scope.aNoData=true;
	    		}
			}
		},function(e){
			$scope.aNoMore=false;
			$scope.aNoData=true;
		});
	}
	
	//初始化违约数据
	$scope.breakProduceList=[];//数据初始化
	var bPage=0;//初始化page为0
	$scope.bNoMore=true;//加载更多
	//查询违约借入信息
	$scope.loadBreakProduceList=function(){
		ZjrProduceService.getProduceListByUserId(3,bPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
	    		if(response.data!=null){
	    			if(response.data.length<=0){
						$scope.bNoMore=false;
						//如果是第一页，并且长度为0，说明一条数据都没有
						if(bPage==0){
							$scope.bNoData=true;
						}
					}else{
						for(var i=0;i<response.data.length;i++){
							$scope.breakProduceList.push(response.data[i]);
						}
						bPage=bPage+1;
					}
	    		}else{
	    			$scope.bNoMore=false;
					//如果为null设置为没有数据图片
					$scope.bNoData=true;
	    		}
			}
		},function(e){
			$scope.bNoMore=false;
			//如果为null设置为没有数据图片
			$scope.bNoData=true;
		});
	}

})

//借入-长贷
.controller('BorrowChangController', function($scope,$stateParams,$window,$state,ZjrProduceService,$state,$ionicHistory,$ionicScrollDelegate) {

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
 $scope.breakDays = function(strDateEnd){
	 var time1 = new Date().Format("yyyy-MM-dd");
     var strDateStart= time1;
   // var strDateEnd ="2015-10-27 10:01:48";
    strDateEnd = strDateEnd.split(' ')[0]
   var strSeparator = "-"; //日期分隔符
   var oDate1;
   var oDate2;
   var iDays;
   oDate1= strDateStart.split(strSeparator);
   oDate2= strDateEnd.split(strSeparator);
   var strDateS = new Date(oDate1[0], oDate1[1]-1, oDate1[2]);
   var strDateE = new Date(oDate2[0], oDate2[1]-1, oDate2[2]);
   iDays = parseInt(Math.abs(strDateS - strDateE ) / 1000 / 60 / 60 /24)//把相差的毫秒数转换为天数
   return iDays;
 }
 $scope.getDate = function(str){
 			   var now = new Date(str);
                var year = now.getFullYear();
                var month =(now.getMonth() + 1).toString();
                var day = (now.getDate()).toString();
                if (month.length == 1) {
                    month = "0" + month;
                }
                if (day.length == 1) {
                    day = "0" + day;
                }
                var dateTime = year+"-"+ month+"-"+day;	
                return dateTime ;
 }               
  
	//返回到我的
	$scope.backMy=function(){
		$state.go('tab.my');
		$ionicHistory.removeBackView();
	}
	
	//设置默认展示为当前
	$scope.borrowStatus=1;
	
	$scope.changeSel=function(v){
		$scope.borrowStatus=v;
		$ionicScrollDelegate.$getByHandle('').scrollTop();
	}
	
	//借不到钱
	$scope.toTip = function(){
		$state.go('tab.addProduceTip02');
	}
	
	//初始化当前数据
	$scope.currentProduceList=[];//数据初始化
	var cPage=0;//初始化page为0
	$scope.cNoMore=true;//加载更多
	//查询当前借入信息
	$scope.loadCurrentProduceList=function(){
		ZjrProduceService.getLongProduceListByUserId(0,cPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
	    		if(response.data!=null){
	    			if(response.data.length<=0){
						$scope.cNoMore=false;
						//如果是第一页，并且长度为0，说明一条数据都没有
						if(cPage==0){
							$scope.cNoData=true;
						}
					}else{
						for(var i=0;i<response.data.length;i++){
							//查询还有多少天还款
/*							var days = new Date(response.data[i].payBackTime).getTime()-new Date().getTime();
							//返回一个整数
							var breakDays=parseInt(days/(1000 * 60 * 60 * 24))+1;*/
							var payBackTime = $scope.getDate(response.data[i].payBackTime)
							//console.log($scope.breakDays(payBackTime));	
							var breakDays=$scope.breakDays(payBackTime);
							response.data[i].breakDays=breakDays;
							$scope.currentProduceList.push(response.data[i]);
						}
						cPage=cPage+1;
					}
	    		}
			}else{
				$scope.cNoMore=false;
				$scope.cNoData=true;
			}
		},function(e){
			$scope.cNoMore=false;
			$scope.cNoData=true;
		});
	}
	
	//初始化已还清数据
	$scope.allReadyProduceList=[];//数据初始化
	var aPage=0;//初始化page为0
	$scope.aNoMore=true;//加载更多
	//查询已还清借入信息
	$scope.loadAllReadyProduceList=function(){
		ZjrProduceService.getLongProduceListByUserId(2,aPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
	    		if(response.data!=null){
	    			if(response.data.length<=0){
						$scope.aNoMore=false;
						//如果是第一页，并且长度为0，说明一条数据都没有
						if(aPage==0){
							$scope.aNoData=true;
						}
					}else{
						for(var i=0;i<response.data.length;i++){
							$scope.allReadyProduceList.push(response.data[i]);
						}
						aPage=aPage+1;
					}
	    		}
			}else{
    			$scope.aNoMore=false;
				//如果为null设置为没有数据图片
				$scope.aNoData=true;
    		}
		},function(e){
			$scope.aNoMore=false;
			//如果为null设置为没有数据图片
			$scope.aNoData=true;
		});
	}
	
	//初始化违约数据
	$scope.breakProduceList=[];//数据初始化
	var bPage=0;//初始化page为0
	$scope.bNoMore=true;//加载更多
	//查询违约借入信息
	$scope.loadBreakProduceList=function(){
		ZjrProduceService.getLongProduceListByUserId(3,bPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
	    		if(response.data!=null){
	    			if(response.data.length<=0){
						$scope.bNoMore=false;
						//如果是第一页，并且长度为0，说明一条数据都没有
						if(bPage==0){
							$scope.bNoData=true;
						}
					}else{
						for(var i=0;i<response.data.length;i++){
							//计算逾期天数
							var days = new Date().getTime()-new Date(response.data[i].payBackTime).getTime();
							var breakDays=parseInt(days/(1000 * 60 * 60 * 24))+1;
							response.data[i].breakDays=breakDays;
							$scope.breakProduceList.push(response.data[i]);
						}
						bPage=bPage+1;
					}
	    		}
			}else{
    			$scope.bNoMore=false;
				//如果为null设置为没有数据图片
				$scope.bNoData=true;
	    	}
		},function(e){
			$scope.bNoMore=false;
			//如果为null设置为没有数据图片
			$scope.bNoData=true;
		});
	}
	
})

//借出-短贷
.controller('LoanDuanController', function($timeout,$rootScope,$sce,$ionicModal,$ionicLoading,$ionicPopup,$scope,$stateParams,$window,$state,LoanService,AttentionService,$ionicScrollDelegate,$ionicHistory,MyService) {

	//返回到我的
	$scope.backMy=function(){
		$state.go('tab.my');
		$ionicHistory.removeBackView();
	}
	
	//借不到钱
	$scope.toTip = function(){
		$state.go('tab.addProduceTip02');
	}
	
	//查询催收记录
	$scope.loanCollection=function(type,produceId){
		$state.go('tab.loanCollection',{"type":type,"produceId":produceId});
	}
	
	//查询数据
	$scope.showUserInfo=function(produceUserId){
		//查询用户资料信息
		//$state.go("tab.userInfo",{searchUserId:produceUserId}); 
/*		   $rootScope.lookCredit=produceUserId;
		   $rootScope.goLookCredit=1;
	       $state.go('tab.zjr');*/
	      $state.go('tab.myCreditCheck',{customerId:produceUserId,type:1});


	}
	
	//查看黑名单
	$scope.toBlack=function(breakRecordId){
		//查询黑名单接口数据
		MyService.getbreakrecordById(breakRecordId).then(function(response) {
			if(response.success=='success'){
				$scope.isOk=true;
				$scope.breakRecord=response.data;
				console.log(response.data);
			}else{
				$scope.isOk=false;
			}
		})
		
		//打开黑名单页面
		$ionicModal.fromTemplateUrl('templates/my/blackInfo.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
		
		//关闭选择联系人方法
		$scope.closeModal = function() {
		    $scope.modal.hide();
		};
	}
	
	//设置默认展示为当前
	$scope.borrowStatus=1;
	//更换标签
	$scope.changeSel=function(v){
		$scope.borrowStatus=v;
		$ionicScrollDelegate.$getByHandle('').scrollTop();
	}
	
	//初始化当前数据
	$scope.currentProduceList=[];//数据初始化
	var cPage=0;//初始化page为0
	$scope.cNoMore=true;//加载更多
	//查询当前借出信息
	$scope.loadCurrentProduceList=function(){
		LoanService.loanList(0,cPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.cNoMore=false;
					if(cPage==0){
						$scope.cNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.currentProduceList.push(response.data[i]);
					}
					cPage=cPage+1;
				}

			}else{
				$scope.cNoMore=false;
				$scope.cNoData=true;
			}
		},function(e){
			$scope.cNoMore=false;
			$scope.cNoData=true;
		});
	}
	
	//初始化已还清数据
	$scope.allReadyProduceList=[];//数据初始化
	var aPage=0;//初始化page为0
	$scope.aNoMore=true;//加载更多
	//查询已还清借出信息
	$scope.loadAllReadyProduceList=function(){
		LoanService.loanList(2,aPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.aNoMore=false;
					if(aPage==0){
						$scope.aNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.allReadyProduceList.push(response.data[i]);
					}
					aPage=aPage+1;
					//console.log($scope.allReadyProduceList);
				}
			}else{
				$scope.aNoMore=false;
				$scope.aNoData=true;
			}
		},function(e){
			$scope.aNoMore=false;
			$scope.aNoData=true;
		});
	}
	
	//初始化违约数据
	$scope.breakProduceList=[];//数据初始化
	var bPage=0;//初始化page为0
	$scope.bNoMore=true;//加载更多
	//查询已还清借出信息
	$scope.loadBreakProduceList=function(){
		LoanService.loanList(3,bPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.bNoMore=false;
					if(bPage==0){
						$scope.bNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						if(response.data[i]===response.data[i-1]){
							i=i-1;
						}
						$scope.breakProduceList.push(response.data[i]);
						
					}
					bPage=bPage+1;
				}
			}else{
				$scope.bNoMore=false;
				$scope.bNoData=true;
			}
		},function(e){
			$scope.bNoMore=false;
			$scope.bNoData=true;
		});
	}
	
	//添加关注
	$scope.addAttention=function(produceUserId){
		//等待
       	$ionicLoading.show({template: '处理中...'});
		AttentionService.addAttention(produceUserId).then(function(response){
			if(response.success=="success"){
				//界面展示为关注
				attention(produceUserId,true);
			}
			
			$ionicLoading.hide();
			$ionicPopup.alert({title:'系统提示',template:response.message});
		},function(e){
			$ionicLoading.hide();
		});
	}
	
	//取消关注
	$scope.deleteAttention = function(produceUserId){
		//等待
       	$ionicLoading.show({template: '处理中...'});
		AttentionService.deleteAttention(produceUserId).then(function(response){
			if(response.success=="success"){
				//界面展示为取消
				attention(produceUserId,false);
			}
			
			$ionicLoading.hide();
			$ionicPopup.alert({title:'系统提示',template:response.message});
		},function(e){
			$ionicLoading.hide();
		});
	}
	
	//取消或增加关注方法
	var attention=function(produceUserId,isOk){
		//取消当前里面的关注
		var produceList=$scope.currentProduceList;
		for(var i=0;i<produceList.length;i++){
			if(produceList[i].produceUserId==produceUserId){
				$scope.currentProduceList[i].isAttention = isOk;
			}
		}
		//取消已还清里面的关注
		produceList=$scope.allReadyProduceList;
		for(var i=0;i<produceList.length;i++){
			if(produceList[i].produceUserId==produceUserId){
				$scope.allReadyProduceList[i].isAttention = isOk;
			}
		}
		
		//取消逾期里面的关注
		produceList=$scope.breakProduceList;
		for(var i=0;i<produceList.length;i++){
			if(produceList[i].produceUserId==produceUserId){
				$scope.breakProduceList[i].isAttention = isOk;
			}
		}
	}

	//查看诚信报告
	$scope.toCredit=function(breakRecordId){
		alert("123");
		//查询黑名单接口数据
		MyService.getbreakrecordById(breakRecordId).then(function(response) {
			if(response.success=='success'){
				$scope.isOk=true;
				$scope.breakRecord=response.data;
			}else{
				$scope.isOk=false;
			}
		})
		
		//打开黑名单页面
		$ionicModal.fromTemplateUrl('templates/my/blackInfo.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
		
		//关闭选择联系人方法
		$scope.closeModal = function() {
		    $scope.modal.hide();
		};
	}
})

//短贷还款
.controller('PayBackDuanController', function($sce,$ionicModal,$stateParams,ZjrProduceService,LoanService,$scope,$ionicPopup,$ionicLoading,$state){
	//查询产品信息
	var produceId=$stateParams.produceId;
	ZjrProduceService.getProduceById(produceId).then(function(response) {
		if(response.success=="success"){
			$scope.produce = response.data;
		}
	});
	
	//查询借给他的信息
	LoanService.loanDetailList(produceId,0).then(function(response) {
		if(response.success=="success"){
			$scope.details = response.data;
		}
		if(response.data==null||response.data.length<=0){
			$scope.detailsShow=false;
		}else{
			$scope.detailsShow=true;
		}
	});
	
	//还款-短贷
	$scope.payBack=function(produce){
		//验证还款时间
		var deadTime=new Date(produce.deadTime).getFullYear()+
		(new Date(produce.deadTime).getMonth()+1)+new Date(produce.deadTime).getDate();
		var nowTime=new Date().getFullYear()+(new Date().getMonth()+1)+new Date().getDate();
		var templateStr="";
		if(deadTime>nowTime){
			templateStr="提前还款将全额扣取利息，你确定要进行还款吗?";
		}else{
			templateStr="你确定要进行还款吗?";
		}

		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: templateStr
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
	       		//等待
	       		 var loading =  $ionicLoading.show({
		      			template: '还款中,请您耐心等候...'
		    	});
	       		//调用还款
				ZjrProduceService.savePayBack(produce.produceId).then(function(response) {
					if(response.success=="success"){
						$ionicLoading.hide();
						//弹出提示并进行页面跳转
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							$state.go('tab.borrowDuan',{},{reload:true});
						});
						
					}else{
						 $ionicLoading.hide();
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
				});
	       }
	    });
		
		
	}
	
	//还款-新手贷
	$scope.payBackXsb=function(produce){
		//验证还款时间
		var deadTime=new Date(produce.deadTime).getFullYear()+
		(new Date(produce.deadTime).getMonth()+1)+new Date(produce.deadTime).getDate();
		var nowTime=new Date().getFullYear()+(new Date().getMonth()+1)+new Date().getDate();
		var templateStr="";
		if(deadTime>nowTime){
			templateStr="提前还款将全额扣取利息，你确定要进行还款吗?";
		}else{
			templateStr="你确定要进行还款吗?";
		}

		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: templateStr
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
	       		//等待
	       		 var loading =  $ionicLoading.show({
		      			template: '还款中,请您耐心等候...'
		    	});
	       		//调用还款
				ZjrProduceService.savePayBackXsb(produce.produceId).then(function(response) {
					if(response.success=="success"){
						$ionicLoading.hide();
						//弹出提示并进行页面跳转
						$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
							$state.go('tab.borrowDuan',{},{reload:true});
						});
						
					}else{
						$ionicLoading.hide();
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
				});
	       }
	    });
		
		
	}
	
	
	//我不借了
	$scope.releaseProduce=function(produceId){
		ZjrProduceService.releaseProduce(produceId).then(function(response) {
			if(response.success=="success"){
				//弹出提示并进行页面跳转
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.borrowDuan');
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
})


//借出-长贷
.controller('LoanChangController', function($sce,$ionicModal,$ionicLoading,$ionicPopup,$scope,$stateParams,$window,$state,LoanService,AttentionService,$ionicHistory,$ionicScrollDelegate,MyService) {

	//返回到我的
	$scope.backMy=function(){
		$state.go('tab.my');
		$ionicHistory.removeBackView();
	}
	
	//借不到钱
	$scope.toTip = function(){
		$state.go('tab.addProduceTip02');
	}
	
	//查看黑名单
	$scope.toBlack=function(breakRecordId){
		//查询黑名单接口数据
		MyService.getbreakrecordById(breakRecordId).then(function(response) {
			if(response.success=='success'){
				$scope.breakRecord=response.data;
				$scope.isOk=true;
			}else{
				$scope.isOk=false;
			}
		})
		
		//打开黑名单页面
		$ionicModal.fromTemplateUrl('templates/my/blackInfo.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
		
		//关闭选择联系人方法
		$scope.closeModal = function() {
		    $scope.modal.hide();
		};
	}
	
	//查询催收记录
	$scope.loanCollection=function(companyUserId,produceId){
		$state.go('tab.loanCollection',{"companyUserId":companyUserId,"produceId":produceId});
	}
	
	//查询数据
	$scope.showUserInfo=function(produceUserId){
		//查询用户资料信息
		//$state.go("tab.userInfo",{searchUserId:produceUserId});
		//alert(123);
/*		$state.go("tab.zjrCreditCheck",{customerId:produceUserId});*/
/*		   $rootScope.lookCredit=produceUserId;
		   $rootScope.goLookCredit=1;
	       $state.go('tab.zjr'); 
*/
$state.go('tab.myCreditCheck',{customerId:produceUserId,type:1});
	}
	
	//设置默认展示为当前
	$scope.borrowStatus=1;
	
	//更换标签
	$scope.changeSel=function(v){
		$scope.borrowStatus=v;
		$ionicScrollDelegate.$getByHandle('').scrollTop();
	}
	
	//初始化当前数据
	$scope.currentProduceList=[];//数据初始化
	var cPage=0;//初始化page为0
	$scope.cNoMore=true;//加载更多
	//查询当前借出信息
	$scope.loadCurrentProduceList=function(){
		LoanService.getLongLoanListByUserId(0,cPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.cNoMore=false;
					if(cPage==0){
						$scope.cNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.currentProduceList.push(response.data[i]);
					}
					cPage=cPage+1
					console.log(response.data);
				}
			}
		});
	}
	
	//初始化已还清数据
	$scope.allReadyProduceList=[];//数据初始化
	var aPage=0;//初始化page为0
	$scope.aNoMore=true;//加载更多
	//查询已还清借出信息
	$scope.loadAllReadyProduceList=function(){
		LoanService.getLongLoanListByUserId(2,aPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.aNoMore=false;
					if(aPage==0){
						$scope.aNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.allReadyProduceList.push(response.data[i]);
					}
					aPage=aPage+1;
				}
			}
		});
	}
	
	//初始化违约数据
	$scope.breakProduceList=[];//数据初始化
	var bPage=0;//初始化page为0
	$scope.bNoMore=true;//加载更多
	//查询已还清借出信息
	$scope.loadBreakProduceList=function(){
		LoanService.getLongLoanListByUserId(3,bPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.bNoMore=false;
					if(bPage==0){
						$scope.bNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.breakProduceList.push(response.data[i]);
					}
					bPage=bPage+1;
				}
			}
		});
	}
	
	//还款记录
	$scope.payBackRecords=function(longLoanRecordId){
		$state.go('tab.payBackDetails',{"longLoanRecordId":longLoanRecordId});
	}
	
	//添加关注
	$scope.addAttention=function(produceUserId){
		AttentionService.addAttention(produceUserId).then(function(response){
			if(response.success=="success"){
				//界面展示为关注
				attention(produceUserId,true);
			}
			$ionicPopup.alert({title:'系统提示',template:response.message});
		});
	}
	
	//取消关注
	$scope.deleteAttention = function(produceUserId){
		AttentionService.deleteAttention(produceUserId).then(function(response){
			if(response.success=="success"){
				//界面展示为取消
				attention(produceUserId,false);
			}
			$ionicPopup.alert({title:'系统提示',template:response.message});
		});
	}
	
	//取消或增加关注方法
	var attention=function(produceUserId,isOk){
		//取消当前里面的关注
		var produceList=$scope.currentProduceList;
		for(var i=0;i<produceList.length;i++){
			if(produceList[i].produceUserId==produceUserId){
				$scope.currentProduceList[i].isAttention = isOk;
			}
		}
		//取消已还清里面的关注
		produceList=$scope.allReadyProduceList;
		for(var i=0;i<produceList.length;i++){
			if(produceList[i].produceUserId==produceUserId){
				$scope.allReadyProduceList[i].isAttention = isOk;
			}
		}
		
		//取消逾期里面的关注
		produceList=$scope.breakProduceList;
		for(var i=0;i<produceList.length;i++){
			if(produceList[i].produceUserId==produceUserId){
				$scope.breakProduceList[i].isAttention = isOk;
			}
		}
	}
	
})

//借出-分期还款列表
.controller('InstalmentListLoanController', function($ionicModal,$stateParams,$scope,LoanService,$ionicHistory,$state){
	//借款记录id
	var longLoanRecordId=$stateParams.longLoanRecordId;
	
	//获取还款状态
	var payBackStatus=$stateParams.payBackStatus;
	$scope.payBackStatus=payBackStatus;
	
	//返回
	$scope.backMy=function(){
		$ionicHistory.goBack();
	}
	
	if(payBackStatus==1){
		//查询分期列表
		LoanService.getLongLoanPayBackById(longLoanRecordId).then(function(response) {
			console.log(response);
			$scope.produceList=response.data;
		});
	}else if(payBackStatus==2){
		//查询分期列表
		LoanService.getAlreadyLoanPayBackById(longLoanRecordId).then(function(response) {
			$scope.produceList=response.data;
		});
	}
	
	
})

//还款列表
.controller('PayBackDetailsController', function($ionicModal,$stateParams,$scope,LoanService,$ionicHistory,$state){
	
	var longLoanRecordId=$stateParams.longLoanRecordId;

	//查询还款明细
	LoanService.getAlreadyLoanPayBackById(longLoanRecordId).then(function(response){
		if(response.success=="success"){
			$scope.produceList=response.data;
		}
	});
	
})

//分期还款列表
.controller('InstalmentListController', function($ionicModal,$stateParams,$scope,LoanService,$ionicHistory,$state){
	//借款记录id
	var longProduceId=$stateParams.longProduceId;
	$scope.longProduceId=longProduceId;
	
	//获取还款状态
	var payBackStatus=$stateParams.payBackStatus;
	$scope.payBackStatus=payBackStatus;
	
	//返回
	$scope.backMy=function(){
		$ionicHistory.goBack(-1);
		$state.go('tab.borrowChang');
	}
	
	//查询分期列表
	LoanService.getLongProducePayBackList(longProduceId).then(function(response) {
		console.log(response);
		$scope.produceList=response.data;
	});
	
	//提前还款
	$scope.payBackT=function(longProduceId){
		$state.go('tab.payBackChangT',{"longProduceId":longProduceId});
	}
	
	//当期还款
	$scope.payBackD=function(account,longProducePayBackId,longProduceId,breakMoney){
		$state.go('tab.payBackChangD',{"account":account,"longProducePayBackId":longProducePayBackId,"longProduceId":longProduceId,"breakMoney":breakMoney});
	}
	
	//去充值
	$scope.recharge=function(){
		//跳转到充值界面
		$state.go('tab.recharge');
	};

	
})

//长贷提前还款
.controller('PayBackChangTController', function($state,$ionicModal,$stateParams,$scope,LoanService,$ionicPopup,MyService){
	//查询长贷借款记录id
	var longProduceId=$stateParams.longProduceId;
	
	//查询帐户余额
	MyService.getAccountByUserId().then(function(response) {
		if(response.success=="success"){		
			var balance = parseFloat(response.data);
			$scope.balance= Number(balance.toFixed(2));	
			console.log($scope.balance);
	       // $scope.balance=response.data;
			//查询提前还款所需要的数据 
				LoanService.getAdvanceByProduceId(longProduceId).then(function(response) {
					if(response.success=="success"){
						$scope.data=response.data;
						var advancePayBack =parseFloat($scope.data.advancePayBack);
						if(advancePayBack.toString().split(".")[1].length>=3){
							advancePayBack=advancePayBack+0.01;
						}		
						$scope.data.advancePayBack=Number(advancePayBack.toFixed(2));
/*						
						console.log($scope.data.advancePayBack);
						console.log(Number($scope.balance)>=Number($scope.data.advancePayBack));*/
						
					}
				});
		}
	});
	
	
	//执行提前还款操作
	$scope.payBack=function(){
		LoanService.saveAdvanceProducePayBack(longProduceId).then(function(response) {
			if(response.success=="success"){
				//弹出提示并进行页面跳转
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.instalmentList',{"longProduceId":longProduceId,"payBackStatus":2});
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	
	//去充值
	$scope.goRecharge=function(){
		$state.go('tab.my',{},{reload:true});
	}
})

//长贷当期还款
.controller('PayBackChangDController', function($state,$ionicModal,$stateParams,$scope,MyService,LoanService,$ionicPopup){
	//查询应还金额
	var account=$stateParams.account;

	
	//逾期金额
	var breakMoney=$stateParams.breakMoney;
	if(breakMoney==null||breakMoney==''||breakMoney<0){
		breakMoney=0;
	}
	$scope.account=parseFloat(account)+parseFloat(breakMoney);
	
	//查询长贷当期还款id
	var longProducePayBackId=$stateParams.longProducePayBackId;
	
	//获取借款记录id
	var longProduceId=$stateParams.longProduceId;
	
	//查询帐户余额
	MyService.getAccountByUserId().then(function(response) {
		if(response.success=="success"){
			$scope.balance=response.data;
		}
	});
		
	
	//执行当期还款操作
	$scope.payBack=function(){
		LoanService.saveProducePayBack(longProducePayBackId).then(function(response) {
			if(response.success=="success"){
				//弹出提示并进行页面跳转
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.instalmentList',{"longProduceId":longProduceId},{reload:true});
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	
	//去充值
	$scope.goRecharge=function(){
		$state.go('tab.my',{},{reload:true});
	}
})

//长贷我不借了
.controller('PayBackChangController', function($state,$ionicModal,$stateParams,$scope,MyService,LoanService,$ionicPopup,ZjrProduceService,$ionicLoading){
	var longProduceId=$stateParams.longProduceId;
	var status=$stateParams.status;
	
	//查询产品明细
	ZjrProduceService.getProduceDetailById(longProduceId).then(function(response) {
		if(response.success=="success"){
			$scope.produce=response.data;
		}
	});
	
	//查询借给他列表
	LoanService.longLoanDetailList(longProduceId,0).then(function(response) {
		if(response.success=="success"){
			$scope.details = response.data;
		}
		if(response.data==null||response.data.length<=0){
			$scope.detailsShow=false;
		}else{
			$scope.detailsShow=true;
		}
	});
	
	//我不借了
	$scope.releaseProduce=function(){
		ZjrProduceService.releaseLongProduce(longProduceId).then(function(response) {
			if(response.success=="success"){
				//弹出提示并进行页面跳转
				$ionicPopup.alert({title:'系统提示',template:response.message}).then(function(res){
					$state.go('tab.borrowChang');
				});
			}else{
				$ionicPopup.alert({title:'系统提示',template:response.message});
			}
		});
	}
	
	//还款-长贷
	$scope.payBack=function(){
		//验证还款时间
		var templateStr="你确定要进行还款吗?";

		//弹出确认对话款
	    var confirmPopup = $ionicPopup.confirm({
	       title: '用户确认',
	       cancelText: '取消',
	       okText: '确定',
	       template: templateStr
	    });
	    confirmPopup.then(function(res) {
	       if(res) {
	       		//等待
	       		var loading =  $ionicLoading.show({
		      		template: '还款中,请您耐心等候...'
		    	});
		    	
	       		//调用当期还款
				LoanService.saveProducePayBack(longProduceId).then(function(response) {
					$ionicLoading.hide();
					if(response.success=="success"){
						//弹出提示并进行页面跳转
						$state.go('tab.borrowChang');
					}else{
						$ionicPopup.alert({title:'系统提示',template:response.message});
					}
				},function(){
					$ionicLoading.hide();
					$ionicPopup.alert({title:'系统提示',template:'对不起，系统好像出了点故障，请稍后再试'});
				});
	       }
	    });
		
		
	}
	
	
})

//消息中心
.controller('MsgController', function($scope,$stateParams,$window,$state,MyService,$ionicHistory,ZjrProduceService,$ionicModal,$ionicScrollDelegate) {

	//默认进入公告
	$scope.msgStatus=1;
	
	//返回到我的
	$scope.backMy=function(){
		$state.go('tab.my');
	}
	
	//切换公告，我的消息
	$scope.changeSel=function(v){
		$scope.msgStatus=v;
		$ionicScrollDelegate.$getByHandle('').scrollTop();
	}
	
	//消息明细
	$scope.msgDetail=function(msg){
		$scope.msg=msg;
		
		//打开消息明细
		$ionicModal.fromTemplateUrl('templates/my/msgDetail.html', {
		    scope: $scope,
		    animation: 'slide-in-up'
		}).then(function(modal) {
		    $scope.modal = modal;
		    $scope.modal.show();
		});
		
		//关闭选择联系人方法
		$scope.closeModal = function() {
		    $scope.modal.hide();
		};
	}
	
	//初始化公告数据
	$scope.ggList=[];//数据初始化
	var gPage=0;//初始化page为0
	$scope.gNoMore=true;//加载更多
	//查询公告
	$scope.loadGMsgList=function(){
		MyService.getPublicMessageList(gPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.gNoMore=false;
					if(gPage==0){
						$scope.gNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.ggList.push(response.data[i]);
					}
					gPage=gPage+1;
				}
			}
		});
	}
	
	//初始化我的数据
	$scope.myMsgList=[];//数据初始化
	var mPage=0;//初始化page为0
	$scope.mNoMore=true;//加载更多
	//查询我的信息
	$scope.loadMyMsgList=function(){
		MyService.getPrivateMessageList(mPage).then(function(response) {
			$scope.$broadcast('scroll.infiniteScrollComplete');
	    	if(response.success=="success"){
				if(response.data.length<=0){
					$scope.mNoMore=false;
					if(mPage==0){
						$scope.mNoData=true;
					}
				}else{
					for(var i=0;i<response.data.length;i++){
						$scope.myMsgList.push(response.data[i]);
					}
					mPage=mPage+1;
				}
			}
		});
	}
	
})

//催收记录查询
.controller('LoanCollectionController', function($scope,$stateParams,ZjrProduceService,$window) {
	//产品id
	var produceId=$stateParams.produceId;
	//类型
	var type=$stateParams.type;
	//构建数据
	var data=new Array();
	
	if(type==1){
		//查询短贷产品信息
		ZjrProduceService.getProduceById(produceId).then(function(response) {
			if(response.success=="success"){
				var deadTime= response.data.deadTime;
				var days = new Date().getTime()-new Date(deadTime).getTime();
				var deadDays=parseInt(days/(1000 * 60 * 60 * 24));
				if(deadDays<6){
					var o=new Object();
					o.content="1-5天：平台通过电话+短信方式通知违约人还款，告知其继续违约将对个人征信产生不良影响";
					o.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+1);
					data.push(o);
				}else if(deadDays>=6&&deadDays<11){
					var o=new Object();
					o.content="1-5天：平台通过电话+短信方式通知违约人还款，告知其继续违约将对个人征信产生不良影响";
					o.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+1);
					data.push(o);
					
					var o1=new Object();
					o1.content="6-10天：违约人将被平台列为征信黑名单，并生成违约人黑名单专属链接，催收短信中会附带该链接并于第5天起逐步推送给违约人联系人。";
					o1.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+6);
					data.push(o1);
				}else if(deadDays>=11){
					var o=new Object();
					o.content="1-5天：平台通过电话+短信方式通知违约人还款，告知其继续违约将对个人征信产生不良影响";
					o.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+1);
					data.push(o);
					
					var o1=new Object();
					o1.content="6-10天：违约人将被平台列为征信黑名单，并生成违约人黑名单专属链接，催收短信中会附带该链接并于第5天起逐步推送给违约人联系人。";
					o1.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+6);
					data.push(o1);
					
					var o2=new Object();
					o2.content="11-15天：平台将逐步电联其联系人，并请其转告逾期人还款。同时开始对接专人做后续催收，并根据逾期时间进一步向违约人委派线下催收团队上门催收，同时启动法律程序追讨欠款。违约人违约征信信息将逐步提交各大互联网搜索引擎，芝麻信用征信管理中心以及中国人民银行个人征信中心等各大征信机构。";
					o2.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+11);
					data.push(o2);
				}
			}
		});
	}else if(type==2){
		//查询短贷产品信息
		ZjrProduceService.getProduceDetailById(produceId).then(function(response) {
			if(response.success=="success"){
				var deadTime= response.data.deadTime;
				var days = new Date().getTime()-new Date(deadTime).getTime();
				var deadDays=parseInt(days/(1000 * 60 * 60 * 24));
				if(deadDays<6){
					var o=new Object();
					o.content="1-5天：平台通过电话+短信方式通知违约人还款，告知其继续违约将对个人征信产生不良影响";
					o.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+1);
					data.push(o);
				}else if(deadDays>=6&&deadDays<11){
					var o=new Object();
					o.content="1-5天：平台通过电话+短信方式通知违约人还款，告知其继续违约将对个人征信产生不良影响";
					o.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+1);
					data.push(o);
					
					var o1=new Object();
					o1.content="6-10天：违约人将被平台列为征信黑名单，并生成违约人黑名单专属链接，催收短信中会附带该链接并于第5天起逐步推送给违约人联系人。";
					o1.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+6);
					data.push(o1);
				}else if(deadDays>=11){
					var o=new Object();
					o.content="1-5天：平台通过电话+短信方式通知违约人还款，告知其继续违约将对个人征信产生不良影响";
					o.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+1);
					data.push(o);
					
					var o1=new Object();
					o1.content="6-10天：违约人将被平台列为征信黑名单，并生成违约人黑名单专属链接，催收短信中会附带该链接并于第5天起逐步推送给违约人联系人。";
					o1.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+6);
					data.push(o1);
					
					var o2=new Object();
					o2.content="11-15天：平台将逐步电联其联系人，并请其转告逾期人还款。同时开始对接专人做后续催收，并根据逾期时间进一步向违约人委派线下催收团队上门催收，同时启动法律程序追讨欠款。违约人违约征信信息将逐步提交各大互联网搜索引擎，芝麻信用征信管理中心以及中国人民银行个人征信中心等各大征信机构。";
					o2.createTime=new Date(new Date(deadTime).getFullYear(),new Date(deadTime).getMonth(),new Date(deadTime).getDate()+11);
					data.push(o2);
				}
			}
		});
	}
	
	//查询催收数据
	ZjrProduceService.getAppLoanCollection(produceId).then(function(response) {
		if(response.success=="success"){
			var array=response.data;
			for(var i=0;i<data.length;i++){
				array.push(data[i]);
			}
			array.sort(function(a,b){
				return (new Date(a.createTime).getTime()-new Date(b.createTime).getTime());
			})
			console.log(array[1]);
			$scope.loanCollections = array.reverse();
		}
	});

})

;